﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=P_DIARY;
    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);
    ui->listView->setEditTriggers(QListView::NoEditTriggers);

    updateDateList();
    selectDate=CurrentDate;
    updateView(selectDate);
    createMenu();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::updateDateList()
{
    QStringList dateList;
    QSqlQuery query;
    query.exec(QString("select date from %1 order by date DESC")
               .arg(table));
    while (query.next()) {
        dateList.append(query.value(0).toString());
    }
    if(!dateList.isEmpty())
        listModel->setStringList(dateList);
}

void Widget::updateView(const QString &date)
{
    if(date.isEmpty())
        return;

    QSqlQuery query;
    query.exec(QString("select content from %1 where date='%2'")
               .arg(table)
               .arg(date));
    if(query.next())
    {
        lastContent=query.value(0).toString();
        ui->content->setPlainText(lastContent);
    }
}

void Widget::on_btn_clean_clicked()
{
    ui->content->clear();
}

bool Widget::addItem(const QString &date, const QString &content)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (date,content) values (?,?)")
                  .arg(table));
    query.addBindValue(date);
    query.addBindValue(content);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

bool Widget::updateItem(const QString &content, const QString &date)
{
    QSqlQuery query;
    QString sql=QString("update %1 set content='%2' where date='%3'")
            .arg(table)
            .arg(content)
            .arg(date);

    if(query.exec(sql))
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void Widget::on_btn_save_clicked()
{
    QString content=ui->content->toPlainText();
    if(content == lastContent)
        return;

    QSqlQuery query;
    query.exec(QString("select id from %1 where date='%2'")
               .arg(table)
               .arg(selectDate));
    if(!query.next())
    {
        QString today=CurrentDate;
        if(addItem(today,content))
        {
            selectDate=today;
            updateDateList();
        }
        else
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("数据无法保存！"));
    }
    else
        if(!updateItem(content,selectDate))
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("数据无法更新！"));
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectDate=index.data().toString();
        updateView(selectDate);
    }
}
